/**
 * @description 路由拦截状态管理
 */

import { getRouterList } from "@/api/route"
import { convertRouter, filterAsyncRoutes } from "@/router/handleRoutes"
import { localroutes } from "@/router/routes"
import { ActionContext } from "vuex"
import { State } from "../interface"

interface RouteState {
  routes: any[]
  partialRoutes: any[]
}

const state = () => ({
  routes: [],
  partialRoutes: [],
})

const getters = {
  routes: (state: RouteState) => state.routes,
  partialRoutes: (state: RouteState) => state.partialRoutes,
}

const mutations = {
  setRoutes(state: RouteState, routes: any[]) {
    state.routes = localroutes.concat(routes)
  }
}

const actions = {
  async setRoutes({ commit }: ActionContext<RouteState, State>, permissions: string[]) {
    console.log(permissions)
    let { data } = await getRouterList()
    console.log(data)
    const finallyAsyncRoutes = filterAsyncRoutes(
      [...data],
      permissions
    )
    console.log(finallyAsyncRoutes)
    let accessRoutes = convertRouter(finallyAsyncRoutes)
    console.log(accessRoutes)
    commit('setRoutes', accessRoutes)
    return accessRoutes
  },
  // async setAllRoutes({ commit }: ActionContext<RouteState, State>) {
  //   let { data } = await getRouterList()
  //   data.push({ path: '*', redirect: '/404', hidden: true })
  //   let accessRoutes = convertRouter(data)
  //   commit('setAllRoutes', accessRoutes)
  //   return accessRoutes
  // }
}
export default { state, mutations, getters, actions }